#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <vector>
#include <sys/types.h>
#include <sys/socket.h>
#include <functional>
#include "Common.hpp"
#include "threadpool.hpp"
#include "LockGuard.hpp"
using task_t=std::function<void()>;

class MessageRoute
{
private:
    bool IsExist(const InetAddr&addr)
    {
        for(auto user:_online_user)
        {
            if(user==addr)//use operator
            {
                return true;
            }
        }
        return false;
    }
public:
    MessageRoute()
    {
        pthread_mutex_init(&_mutex,nullptr);
    }
    void AddUser(const InetAddr&addr)
    {   
        LockGuard guard(&_mutex);
        if(IsExist(addr))
        {
            return;
        }
        _online_user.push_back(addr);
    }
    void DelUser(const InetAddr&addr)
    {
        LockGuard guard(&_mutex);
        for(auto it=_online_user.begin();it!=_online_user.end();it++)
        {
            if(*it==addr)
            {
                _online_user.erase(it);
                break;
            }
        }
    }
    void RouteHelper(int sockfd,const std::string message)//统一进行消息转发
    {
        LockGuard guard(&_mutex);
        for(auto user:_online_user)
        {
            struct sockaddr_in addr=user.Addr();
            ::sendto(sockfd,message.c_str(),sizeof(message),0,(struct sockaddr*)&addr,sizeof(addr));//调用原生接口 发信息
        }
    }
    void Route(int fd,const std::string message,const InetAddr who)
    {
        AddUser(who);//添加用户
        //处理用户信息
        if(message=="Q"||message=="q"||
          message=="quit"||message=="退出")
        {
            DelUser(who);
        }
        //构建任务对象,入线程池->转发
        task_t t=std::bind(&MessageRoute::RouteHelper,this,fd,message);
        threadpool<task_t>::Getinstance()->Enqueue(t);//入单例池
    }
    ~MessageRoute()
    {
        pthread_mutex_destroy(&_mutex);
    }


    private:
    std::vector<InetAddr>_online_user;
    pthread_mutex_t _mutex;
};